﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

namespace GBT.Tool.Core
{
    public class DataPaging
    {
        /// <summary>
        /// 分页处理函数
        /// </summary>
        /// <param name="CurrentPage">当前需要获取数据的页面</param>
        /// <param name="jaParam">数据集合</param>
        /// <returns></returns>
        public JObject PagingProcessing(int CurrentPage, JArray jaParam)
        {
            int PageCount = 20;//每页数量
            decimal DataCount = jaParam.Count;//数据总数量
            decimal PageTotal = Math.Ceiling(DataCount / PageCount);//页面数量
            decimal LastPageCount = DataCount - ((PageTotal - 1) * PageCount);//最后一页数量

            JObject joResult = new JObject();
            JArray jaResult = new JArray();
            JObject joItem = new JObject();

            int CurrentIndex = 0;//当前需要获取的页面的数据索引开始
            int CurrentMaxIndex = PageCount;
            if (CurrentPage == 1 && DataCount > PageCount)
            {
                for (int dataIndex = CurrentIndex; dataIndex < CurrentMaxIndex; dataIndex++)
                {
                    joItem = (JObject)jaParam[dataIndex];
                    jaResult.Add(joItem);
                }
            }
            else if (CurrentPage > 1 && CurrentPage < PageTotal)//第2页到倒数第二页
            {
                CurrentIndex = (CurrentPage - 1) * PageCount;
                CurrentMaxIndex = PageCount * CurrentPage;
                for (int dataIndex = CurrentIndex; dataIndex < CurrentMaxIndex; dataIndex++)
                {
                    joItem = (JObject)jaParam[dataIndex];
                    jaResult.Add(joItem);
                }
            }
            else if (CurrentPage == PageTotal)//最后一页
            {
                CurrentIndex = (CurrentPage - 1) * PageCount;
                for (int dataIndex = CurrentIndex; dataIndex < DataCount; dataIndex++)
                {
                    joItem = (JObject)jaParam[dataIndex];
                    jaResult.Add(joItem);
                }
            }

            joResult.Add("pageTotal", PageTotal);
            joResult.Add("dataCount", DataCount);
            joResult.Add("message", "ok");
            joResult.Add("state", true);
            joResult.Add("data", jaResult);

            return joResult;
        }
    }
}
